
package com.smartstate.iot.config.redis;

import cn.hutool.core.date.DateUtil;
import com.smartstate.common.util.FormatNumUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

@Component
public class CacheService {
    @Resource
    RedisTemplate<String, Object> redisTemplate;

    public String getIncrementNumByDate(String key,int formatLength) {
        String incrementNum = this.getIncrementNum(key, formatLength);
        return DateUtil.format(LocalDateTime.now(), "yyyyMMdd") + incrementNum;
    }

    public String getIncrementNumByDate(String key,int formatLength,String format) {
        String incrementNum = this.getIncrementNum(key, formatLength);
        return DateUtil.format(LocalDateTime.now(), "yyyyMMdd") + incrementNum;
    }

    public String getIncrementNum(String key,int formatLength) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long counter = entityIdCounter.incrementAndGet();
        if (counter.longValue() == 1) {
            entityIdCounter.expire(CacheService.getSecondsNextEarlyMorning(), TimeUnit.SECONDS);
        }
        String counterStr = FormatNumUtils.frontCompWithZero(formatLength, counter);
        return counterStr;
    }
    /**
     * 判断当前时间距离第二天凌晨的秒数
     */
    public static Long getSecondsNextEarlyMorning() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }
}